package com.shenmazong.demowebsocket.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/websocket")
@Slf4j
public class MyWebSocket {
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();
    private Session _senssion;

    @OnOpen
    public void onOpen(Session session) {
        this._senssion = session;
        onlineSessions.put(session.getId(), session);
        log.info("来新用户了......"+onlineSessions.size());

        sendMessageAll("有新用户来了");
    }

    @OnClose
    public void onClose(Session session) {
        onlineSessions.remove(session.getId());
        log.info("用户跑了......");
    }

    @OnMessage
    public void onMessage(String message, Session session){
        log.info("收到消息："+message);

        //sendMessage(message, session);
        sendMessageAll(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info("连接出错了......");
        error.printStackTrace();
    }

    public void sendMessage(String message, Session session) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessageAll(String message) {
        try {
            for(String key:onlineSessions.keySet()) {
                Session session = onlineSessions.get(key);
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
